package com.hernandez.games.adventures.views;

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JPanel;

import com.hernandez.games.adventures.beans.Resolution;
import com.hernandez.games.adventures.beans.Window;
import com.hernandez.games.adventures.controllers.EventController;
import com.hernandez.games.adventures.events.ExitEvent;
import com.hernandez.games.adventures.events.KeyboardEvent;

public class GameCanvas implements ICanvas {
	private BufferStrategy strategy;
	private JFrame window;
	private Canvas canvas;

	public GameCanvas(Window win) {
		canvas = new Canvas();
		window = new JFrame(win.getTitle());
		Resolution res = win.getResolution();
		JPanel panel = (JPanel) window.getContentPane();
		panel.setPreferredSize(new Dimension(res.getWidth(), res.getHeight()));
		panel.setLayout(null);
		canvas.setBounds(0, 0, res.getWidth(), res.getHeight());
		panel.add(canvas);
		canvas.setIgnoreRepaint(true);
		window.pack();
		window.setResizable(false);
		window.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				EventController.getInstance().publishEvent(ExitEvent.newEvent());
			}
		});
		canvas.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				EventController.getInstance().publishEvent(new KeyboardEvent(e.getKeyChar(), KeyboardEvent.KeyboardEventType.TYPED));
				super.keyTyped(e);
			}
			@Override
			public void keyReleased(KeyEvent e) {
				EventController.getInstance().publishEvent(new KeyboardEvent(e.getKeyChar(), KeyboardEvent.KeyboardEventType.RELEASED));
				super.keyReleased(e);
			}
			@Override
			public void keyPressed(KeyEvent e) {
				EventController.getInstance().publishEvent(new KeyboardEvent(e.getKeyChar(), KeyboardEvent.KeyboardEventType.PRESSED));
				super.keyPressed(e);
			}
		});
	}
	
	@Override
	public void show() {
		window.setVisible(true);
		canvas.requestFocus();
		canvas.createBufferStrategy(2);
		strategy = canvas.getBufferStrategy();
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub
		window.dispose();
	}
}
